#include <string.h>
#include "app_common.h"
#include "cJSON/cJSON.h"
#include <stdlib.h>
#include "log/log.h"
/**
 * @brief 将字符数组格式消息转换为json格式消息
 * @param chars  字符数组消息
 * @param len    字符数组数据长度
 * @return json消息
 */
/**
 字符数组:  1 2 4 XXabcd
 json字符串: {"conn_type": 1, "id": "5858", "msg": "61626364"}
 */
char *app_message_charsToJson(char *chars, int len)
{
   // 从chars中取出：conn_type/id_len/msg_len / id / msg
   int conn_type = chars[0];
   int id_len = chars[1];
   int msg_len = chars[2];
   char id[id_len];
   char msg[msg_len];
   memcpy(id, chars + 3, id_len);
   memcpy(msg, chars + 3 + id_len, msg_len);

   // 将id和msg转换为十六进制字符串： app_common_charsToHexstr
   char *id_hexstr = app_common_charsToHexstr(id, id_len);
   char *msg_hexstr = app_common_charsToHexstr(msg, msg_len);

   // 生成包含conn_type, id_hexstr,msg_hexstr的json字符串
   cJSON *root_obj = cJSON_CreateObject();//创建一个JSON对象
   cJSON_AddNumberToObject(root_obj, "conn_type", conn_type);
   cJSON_AddStringToObject(root_obj, "id", id_hexstr);
   cJSON_AddStringToObject(root_obj, "msg", msg_hexstr);
   char *json = cJSON_PrintUnformatted(root_obj);//将JSON对象转换为字符串

   // 释放内存
   cJSON_Delete(root_obj);
   free(id_hexstr);
   free(msg_hexstr);

   // 返回json消息
   return json;
}

/**
 * @brief 将json格式消息转换为字符数组格式消息
 * @param json   json消息
 * @param chars_buf  字符数组消息的缓存容器
 * @param buf_len    缓存容器大小
 * @return 成功：字符数组消息的长度，失败：-1
 */
int app_message_jsonToChars(char *json, char *chars_buf, int buf_len)
{
         // 解析json，得到conn_type,id_hexstr,msg_hexstr
    cJSON *root_obj = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root_obj, "conn_type")->valueint;
    char *id_hexstr = cJSON_GetObjectItem(root_obj, "id")->valuestring;
    char *msg_hexstr = cJSON_GetObjectItem(root_obj, "msg")->valuestring;
    // 将十六进制字符串id_hexstr和msg_hexstr转换为字符数组id和msg app_common_hexstrToChars
    int id_len = -1;
    int msg_len = -1;
    char *id_chars = app_common_hexstrToChars(id_hexstr, &id_len);
    char *msg_chars = app_common_hexstrToChars(msg_hexstr, &msg_len);

    // 字符数组消息的长度
    int chars_len = 3 + id_len + msg_len;
    // 检查容器是否够大
    if (chars_len > buf_len)
    {
        log_error("buf_len is too small");
        return -1;
    }

    // 将数据写入容器chars_buf
    chars_buf[0] = conn_type;
    chars_buf[1] = id_len;
    chars_buf[2] = msg_len;
    memcpy(chars_buf + 3, id_chars, id_len);
    memcpy(chars_buf + 3 + id_len, msg_chars, msg_len);

    // 释放内存
    cJSON_Delete(root_obj);
    free(id_chars);
    free(msg_chars);

    // 返回字符数组消息的长度
    return chars_len;
}